/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.modulelink.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Bean工具类
 * 
 * @author jianggujin
 *
 */
public class JBeanUtils {
    /**
     * 查找指定名称与参数类型的方法
     * 
     * @param clazz
     * @param name
     * @param parameterTypes
     * @return
     */
    public static Method findMethod(Class<?> clazz, String name, Class<?>... parameterTypes) {
        Method method = null;
        while (clazz != null && !Object.class.equals(clazz)) {
            try {
                method = clazz.getDeclaredMethod(name, parameterTypes);
                break;
            } catch (NoSuchMethodException e) {
                clazz = clazz.getSuperclass();
            }
        }
        return method;
    }

    /**
     * 执行指定对象的指定方法
     * 
     * @param obj
     * @param method
     * @param parameters
     * @return
     */
    public static Object invokeMethod(Object obj, Method method, Object... parameters) {
        boolean accessible = method.isAccessible();
        try {
            method.setAccessible(true);
            return method.invoke(obj, parameters);
        } catch (Exception e) {
            throw JExceptionUtils.handleException(e);
        } finally {
            method.setAccessible(accessible);
        }
    }

    public static Type[] getComponentType(Field field) {
        Type type = field.getGenericType();
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            return parameterizedType.getActualTypeArguments();
        }
        return null;
    }
}
